package logic

import (
	"context"
	"errors"
	"user-srv/internal/svc"
	"user-srv/model/mysql"
	"user-srv/model/redis"
	"user-srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	u := mysql.User{
		Mobile:   in.Mobile,
		Password: in.Password,
	}
	sms, err := redis.GetSendSms(in.Mobile)
	if err != nil {
		return nil, err
	}
	if in.Code != sms {
		return nil, errors.New("短信验证码错误")
	}
	err = u.FindMobile()
	if err != nil {
		err = u.CreateUser()
		if err != nil {
			return nil, errors.New("注册用户失败")
		}
	}
	return &user.UserLoginResponse{UserId: int64(u.ID)}, nil
}
